package com.example.bankmanage.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.bankmanage.convention.exception.ClientException;
import com.example.bankmanage.dto.rep.*;
import com.example.bankmanage.entity.PageBean;
import com.example.bankmanage.entity.accounts;
import com.example.bankmanage.entity.cards;
import com.example.bankmanage.mapper.CardMapper;
import com.example.bankmanage.service.CardService;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.OutputStream;
import java.util.List;
import java.util.stream.Collectors;

import static com.example.bankmanage.convention.errorcode.UserErrorCodeEnum.CARD_ADD_ERROR;
import static com.example.bankmanage.convention.errorcode.UserErrorCodeEnum.CARD_UPDATE_ERROR;

@Service
@SuppressWarnings("all")
public class CardServiceimpl extends ServiceImpl<CardMapper, cards> implements CardService {
    @Autowired
    private CardMapper cardMapper;
    @Override
    public PageBean<cards> fetchCardList(CardReqDTO requestParam) {
        Page<cards> page = new Page<>(requestParam.getPage(), requestParam.getSize());

        // 构建查询条件
        LambdaQueryWrapper<cards> queryWrapper = new LambdaQueryWrapper<>();
//        System.out.println(requestParam.getCardNumber() != "");
        // 添加查询条件
        queryWrapper.eq(requestParam.getCardNumber() != null && requestParam.getCardNumber() != "", cards::getCardNumber, requestParam.getCardNumber())
                .eq(requestParam.getCardType() != null && requestParam.getCardType() != "",cards::getCardType, requestParam.getCardType())
                .eq(requestParam.getStatus() != null && requestParam.getStatus() != "", cards::getStatus, requestParam.getStatus())
                .eq(requestParam.getAccountId() != null, cards::getAccountId, requestParam.getAccountId());

//        // 添加排序条件
//        if (StringUtils.isNotBlank(requestParam.getSortField()) && StringUtils.isNotBlank(requestParam.getSortOrder())) {
//            queryWrapper.orderBy(true, "asc".equalsIgnoreCase(requestParam.getSortOrder()),
//                    getSortField(requestParam.getSortField()));
//        } else {
//            // 默认按账单ID降序
//            queryWrapper.orderByDesc(bills::getBillId);
//        }
        page = baseMapper.selectPage(page, queryWrapper);
//        System.out.println(page.getPages());
//        System.out.println(page.getTotal());
        //这里的mybatis-plus里的count指令没有执行,要调
        PageBean<cards> pageBean = new PageBean<>();
        pageBean.setContent(page.getRecords());
        pageBean.setTotalElements(page.getTotal());
        // 执行查询
        return pageBean;
    }

    @Override
    public cards getCardDetail(Integer cardId) {
        LambdaQueryWrapper<cards> QueryWrapper = Wrappers.lambdaQuery(cards.class)
                .eq(cards::getCardId, cardId);
        cards cards1 = baseMapper.selectOne(QueryWrapper);
        return cards1;
    }

    @Override
    public void createCard(CreateCardReqDTO requestParam) {
        int insert = baseMapper.insert(BeanUtil.toBean(requestParam, cards.class));
        if(insert < 1){
            throw new ClientException(CARD_ADD_ERROR);
        }
    }

    @Override
    public void updateCard(Integer cardId, UpdateCardReqDTO requestParam) {
        cards card = BeanUtil.toBean(requestParam,cards.class);
        card.setCardId(null);
        LambdaUpdateWrapper<cards> UpdateWrapper = Wrappers.lambdaUpdate(cards.class)
                .eq(cards::getCardId, cardId);
        int update = baseMapper.update(card, UpdateWrapper);
        if(update < 1){
            throw new ClientException(CARD_UPDATE_ERROR);
        }
    }

    @Override
    public void exportCard(CardExportReqDTO exportDTO, OutputStream outputStream) {
//        LambdaQueryWrapper<cards> QueryWrapper = Wrappers.lambdaQuery(cards.class)
//                .eq(cards::getCardNumber, exportDTO.getCardNumber())
//                .eq(cards::getCardId, exportDTO.getAccountId())
//                .eq(cards::getStatus, exportDTO.getStatus())
//                .eq(cards::getAccountId, exportDTO.getAccountId())
//                .ge(cards::getExpiryDate, exportDTO.getStartDate())
//                .le(cards::getExpiryDate, exportDTO.getEndDate());
//        Page<cards> p = baseMapper.selectPage(BeanUtil.toBean(exportDTO,cards.class),QueryWrapper);
        // 1. 查询数据
        List<cards> card = cardMapper.selectCardsForExport(exportDTO);
        System.out.println(card);
        if (CollectionUtils.isEmpty(card)) {
            throw new RuntimeException("没有可导出的数据");
        }

        // 2. 导出Excel
        try (ExcelWriter excelWriter = EasyExcel.write(outputStream)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) // 自动列宽
                .build()) {

            WriteSheet writeSheet = EasyExcel.writerSheet("账单数据")
                    .head(CardExportReqDTO.class)
                    .registerWriteHandler(new HorizontalCellStyleStrategy(
                            getHeaderStyle(),
                            getContentStyle())) // 自定义样式
                    .build();

            // 3. 数据转换并写入Excel
            excelWriter.write(convertToExcelVO(card), writeSheet);
            excelWriter.finish(); // 确保写入完成
        }
    }

    private List<CardExportReqDTO> convertToExcelVO(List<cards> account) {
        return account.stream().map(bill -> {
            CardExportReqDTO vo = new CardExportReqDTO();
            // 这里进行属性拷贝
            BeanUtils.copyProperties(bill, vo);
            // 特殊字段处理
            vo.setStatus(String.valueOf(bill.getStatus()));
            return vo;
        }).collect(Collectors.toList());
    }
    // 内容单元格样式
    private WriteCellStyle getContentStyle() {
        WriteCellStyle style = new WriteCellStyle();

        // 1. 对齐方式
        style.setHorizontalAlignment(HorizontalAlignment.CENTER); // 水平居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);   // 垂直居中

        // 2. 边框设置
        style.setBorderLeft(BorderStyle.THIN);          // 左边框
        style.setBorderRight(BorderStyle.THIN);         // 右边框
        style.setBorderTop(BorderStyle.THIN);           // 上边框
        style.setBorderBottom(BorderStyle.THIN);        // 下边框
        style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); // 边框颜色
        style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());

        // 3. 背景色（默认白色，可不设置）
        style.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
        style.setFillForegroundColor(IndexedColors.WHITE.getIndex());

        // 4. 字体样式
        WriteFont font = new WriteFont();
        font.setFontName("宋体");                       // 字体
        font.setFontHeightInPoints((short) 11);        // 字号
        font.setColor(IndexedColors.BLACK.getIndex()); // 字体颜色
        style.setWriteFont(font);

        // 5. 自动换行（根据需求）
        style.setWrapped(true);

        return style;
    }
    // 自定义表头样式
    private WriteCellStyle getHeaderStyle() {
        WriteCellStyle style = new WriteCellStyle();
        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        style.setHorizontalAlignment(HorizontalAlignment.CENTER);
        // 其他样式设置...
        return style;
    }
}
